import React, { useState, useMemo, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom'
import { setcity } from '../fatuter/ditu';
// 热门城市数据
const hotCities = ['上海', '北京', '广州', '成都', '三亚', '杭州', '西安', '南京', '厦门'];

// 完整的城市数据（按字母分组）
const cityData = {
  A: ['安丘，潍坊', '安化，益阳', '安吉，湖州', '安图', '安平，衡水', '安庆', '安康'],
  B: ['北京', '包头', '保定', '北海', '巴中', '蚌埠', '本溪', '滨州', '宝鸡', '白银'],
  C: ['成都', '重庆', '长春', '长沙', '沧州', '常州', '承德', '滁州', '郴州', '常德'],
  D: ['大连', '东莞', '大庆', '东营', '德州', '大同', '丹东', '德阳', '达州', '大理'],
  E: ['鄂尔多斯', '恩施', '鄂州', '峨眉山'],
  F: ['福州', '佛山', '抚顺', '阜阳', '抚州', '防城港', '富阳'],
  G: ['广州', '贵阳', '桂林', '赣州', '广元', '广安', '贵港', '固原'],
  H: ['杭州', '合肥', '哈尔滨', '海口', '呼和浩特', '惠州', '湖州', '邯郸', '衡阳'],
  J: ['济南', '青岛', '金华', '嘉兴', '吉林', '九江', '江门', '晋中', '锦州', '吉安'],
  K: ['昆明', '开封', '喀什', '克拉玛依', '库尔勒', '昆山'],
  L: ['兰州', '拉萨', '洛阳', '临沂', '柳州', '连云港', '聊城', '丽水', '泸州', '乐山'],
  M: ['绵阳', '马鞍山', '茂名', '梅州', '牡丹江', '眉山'],
  N: ['南京', '宁波', '南宁', '南昌', '南通', '南充', '宁德', '内江', '南阳'],
  P: ['平顶山', '盘锦', '莆田', '萍乡', '攀枝花', '普洱'],
  Q: ['青岛', '泉州', '秦皇岛', '齐齐哈尔', '衢州', '清远', '钦州', '曲靖'],
  R: ['日照', '瑞安'],
  S: ['上海', '深圳', '苏州', '沈阳', '石家庄', '绍兴', '三亚', '宿迁', '绥化', '十堰'],
  T: ['天津', '太原', '唐山', '泰安', '台州', '泰州', '铁岭', '通辽', '天水'],
  W: ['武汉', '无锡', '温州', '威海', '潍坊', '芜湖', '乌鲁木齐', '梧州', '渭南'],
  X: ['西安', '厦门', '徐州', '西宁', '湘潭', '襄阳', '新乡', '邢台', '咸阳'],
  Y: ['烟台', '扬州', '银川', '盐城', '宜昌', '岳阳', '运城', '宜宾', '永州', '延边'],
  Z: ['郑州', '珠海', '淄博', '镇江', '张家口', '中山', '舟山', '漳州', '遵义', '株洲']
};

// 字母导航（按实际数据排序）
const letters = Object.keys(cityData).sort();

interface CitySelectorProps {
  currentCity: string;
  historyCities: string[];
  onSelectCity: (city: string) => void;
  onClose?: () => void;
}

const CitySelector: React.FC<CitySelectorProps> = ({ 
  currentCity, 
  historyCities, 
  onSelectCity, 
  onClose 
}) => {
  const [search, setSearch] = useState('');
  const [selectedLetter, setSelectedLetter] = useState<string>('');

  // 过滤历史城市（去重且不包含当前城市）
  const historyFiltered = useMemo(() => {
    return Array.from(new Set(historyCities))
      .filter(city => city !== currentCity)
      .slice(0, 5);
  }, [historyCities, currentCity]);

  // 根据搜索关键字过滤城市数据
  const filteredCityData = useMemo(() => {
    if (!search.trim()) return cityData;
    
    const searchLower = search.trim().toLowerCase();
    const result: Record<string, string[]> = {};
    
    for (const [letter, cities] of Object.entries(cityData)) {
      const filteredCities = cities.filter(city => 
        city.toLowerCase().includes(searchLower)
      );
      if (filteredCities.length > 0) {
        result[letter] = filteredCities;
      }
    }
    
    return result;
  }, [search]);

  // 处理字母导航点击
  const handleLetterClick = (letter: string) => {

    setSelectedLetter(letter);
    const element = document.getElementById(`city-group-${letter}`);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };
const dispatch = useDispatch()
const  navigate     = useNavigate()
  // 处理城市选择 - 添加安全检查
  const handleCitySelect = (city: string) => {
      dispatch(setcity(city))
      navigate('/home')
  };

  // 重置选中字母当搜索时
  useEffect(() => {
    if (search.trim()) {
      setSelectedLetter('');
    }
  }, [search]);

  return (
    <div
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: '#fff',
        zIndex: 1000,
        overflow: 'hidden',
        fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
      }}
    >
      {/* 搜索栏 */}
      <div
        style={{
          padding: '12px 16px',
          borderBottom: '1px solid #f0f0f0',
          backgroundColor: '#f8f8f8',
        }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            backgroundColor: '#fff',
            borderRadius: '8px',
            padding: '8px 12px',
            border: '1px solid #e0e0e0',
          }}
        >
          <span style={{ marginRight: '8px', color: '#999' }}>🔍</span>
          <input
            type="text"
            placeholder="搜索城市"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            style={{
              border: 'none',
              outline: 'none',
              fontSize: '16px',
              flex: 1,
              backgroundColor: 'transparent',
            }}
            autoFocus
          />
          {search && (
            <button
              onClick={() => setSearch('')}
              style={{
                border: 'none',
                background: 'transparent',
                fontSize: '18px',
                color: '#999',
                cursor: 'pointer',
              }}
            >
              ×
            </button>
          )}
        </div>
      </div>

      {/* 主要内容区域 */}
      <div
        style={{
          height: 'calc(100vh - 60px)',
          overflowY: 'auto',
          position: 'relative',
        }}
      >
        {/* 当前/历史区域 */}
        <section style={{ padding: '16px', borderBottom: '1px solid #f0f0f0' }}>
          <div
            style={{
              fontSize: '14px',
              fontWeight: '600',
              color: '#333',
              marginBottom: '12px',
            }}
          >
            当前/历史
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
            {/* 当前城市 */}
            <button
              onClick={() => handleCitySelect(currentCity)}
              style={{
                padding: '6px 16px',
                borderRadius: '16px',
                border: '1px solid #007AFF',
                backgroundColor: '#e6f3ff',
                color: '#007AFF',
                fontSize: '14px',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
              }}
            >
              <span style={{ marginRight: '4px' }}>📍</span>
              {currentCity}
            </button>
            
            {/* 历史城市 */}
            {historyFiltered.map((city) => (
              <button
                key={city}
                onClick={() => handleCitySelect(city)}
                style={{
                  padding: '6px 16px',
                  borderRadius: '16px',
                  border: '1px solid #e0e0e0',
                  backgroundColor: '#f5f5f5',
                  color: '#333',
                  fontSize: '14px',
                  cursor: 'pointer',
                }}
              >
                {city}
              </button>
            ))}
          </div>
        </section>

        {/* 热门城市区域 */}
        <section style={{ padding: '16px', borderBottom: '1px solid #f0f0f0' }}>
          <div
            style={{
              fontSize: '14px',
              fontWeight: '600',
              color: '#333',
              marginBottom: '12px',
            }}
          >
            热门城市
          </div>
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(3, 1fr)',
              gap: '12px',
            }}
          >
            {hotCities.map((city) => (
              <button
                key={city}
                onClick={() => handleCitySelect(city)}
                style={{
                  padding: '10px 0',
                  border: '1px solid #e0e0e0',
                  backgroundColor: '#fff',
                  borderRadius: '6px',
                  fontSize: '14px',
                  color: '#333',
                  cursor: 'pointer',
                  textAlign: 'center',
                }}
              >
                {city}
              </button>
            ))}
          </div>
        </section>

        {/* 城市列表区域 */}
        <div style={{ paddingBottom: '20px' }}>
          {Object.entries(filteredCityData).map(([letter, cities]) => (
            <section
              key={letter}
              id={`city-group-${letter}`}
              style={{ padding: '0 16px' }}
            >
              <div
                style={{
                  fontSize: '16px',
                  fontWeight: '600',
                  color: '#333',
                  padding: '12px 0',
                  borderBottom: '1px solid #f0f0f0',
                  position: 'sticky',
                  top: 0,
                  backgroundColor: '#fff',
                  zIndex: 1,
                }}
              >
                {letter}
              </div>
              <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
                {cities.map((city) => (
                  <li
                    key={city}
                    style={{
                      padding: '14px 0',
                      borderBottom: '1px solid #f5f5f5',
                    }}
                  >
                    <button
                      onClick={() => handleCitySelect(city.split('，')[0])}
                      style={{
                        width: '100%',
                        border: 'none',
                        background: 'transparent',
                        color: '#333',
                        fontSize: '16px',
                        textAlign: 'left',
                        cursor: 'pointer',
                        padding: 0,
                      }}
                    >
                      {city}
                    </button>
                  </li>
                ))}
              </ul>
            </section>
          ))}
        </div>

        {/* 字母导航侧边栏 */}
        <div
          style={{
            position: 'fixed',
            right: '8px',
            top: '50%',
            transform: 'translateY(-50%)',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            zIndex: 100,
            backgroundColor: 'rgba(255,255,255,0.9)',
            borderRadius: '12px',
            padding: '8px 4px',
          }}
        >
          {letters.map((letter) => (
            <button
              key={letter}
              onClick={() => handleLetterClick(letter)}
              style={{
                border: 'none',
                background: 'transparent',
                fontSize: '12px',
                color: selectedLetter === letter ? '#007AFF' : '#666',
                padding: '2px 6px',
                cursor: 'pointer',
                fontWeight: selectedLetter === letter ? '600' : 'normal',
              }}
            >
              {letter}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

export default CitySelector;